//
//  LYDataBaseMigrateManager.m
//  Apps
//
//  Created by 李永彬 on 2019/6/5.
//  Copyright © 2019 appscomm. All rights reserved.
//

#import "LYDataBaseMigrateManager.h"
#import "LYDataBaseMigrationAction.h"
#import "LYDatabase+Migrate.h"
#import "LYDBMigrateTool.h"

#define versionTableName @"t_MigrationVersion"
#define cloumn_Version @"version"
@interface LYDataBaseMigrateManager ()

@end

@implementation LYDataBaseMigrateManager

//+ (instancetype)sharedManager {
//    static LYDataBaseMigrateManager *_instance = nil;
//    static dispatch_once_t onceToken;
//    
//    dispatch_once(&onceToken, ^{
//        _instance = [[LYDataBaseMigrateManager alloc] init];
//    });
//    return _instance;
//}

- (instancetype)initWithDatabase:(LYDatabase *)database delegate:(id <LYDataBaseMigrateManagerDelegate> )delegate {
    self = [super init];
    if (self) {
        self.delegate = delegate;
        self.database = database;
    }
    return self;
}

- (void)startMigrateWithProgressHandler:(void(^)(NSProgress *progress))progressHandler completion:(void(^)(void))completion {
    [LYDatabase database].logOn = NO;
    
    __block NSInteger oldVersion = [self DBVersion];
    
    if ([self.delegate conformsToProtocol:@protocol(LYDataBaseMigrateManagerDelegate)] && [self.delegate respondsToSelector:@selector(databaseMigrateSteps)]) {
        
        if ([self.delegate databaseMigrateSteps].count) {
            NSProgress *currentProgress = [NSProgress progressWithTotalUnitCount:self.delegate.databaseMigrateSteps.count];
            
            [[self.delegate databaseMigrateSteps] enumerateObjectsUsingBlock:^(id<LYDBMigrateStepProtocol>  _Nonnull step, NSUInteger index, BOOL * _Nonnull stop) {
                
                //当前版本号大于旧的版本号时更新
                if (step.completeVersion == oldVersion + 1) {
                    NSError *err = nil;
                    
                    if (@available(iOS 9.0, *)) {
                    }
                    else {
                        [currentProgress becomeCurrentWithPendingUnitCount:index + 1];
                    }
                    
                    __block NSProgress *currentStepProgress = nil;
                    [step goUpActionWithCurrentDBVersion:oldVersion progressHandler:^(NSProgress * _Nonnull progress) {
                        
                        if (currentStepProgress != progress) {
                            currentStepProgress = progress;
                            if (@available(iOS 9.0, *)) {
                                [currentProgress addChild:currentStepProgress withPendingUnitCount:1];
                            }
                        }
                        
                        if (progressHandler) {
                            progressHandler(currentProgress);
                        }
                        
                    } error:&err];
                    
                    if (@available(iOS 9.0, *)) {
                    }
                    else {
                        [currentProgress resignCurrent];
                    }
                    
                    if (err) {
                        [step goDownActionWithError:&err];
                        [currentProgress cancel];
                        return;
                    }
                    
                    [currentProgress setCompletedUnitCount:index + 1];
                    if (progressHandler) {
                        progressHandler(currentProgress);
                    }
                    
                    [self setDBVersion:step.completeVersion];
                    oldVersion = [self DBVersion];
                    
                }
            }];
        }
    }
    
    if (completion) {
        completion();
    }
}

- (void)startAsyncMigrateWithProgressHandler:(void(^)(NSProgress *progress))progressHandler completion:(void(^)(void))completion {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        [self startMigrateWithProgressHandler:progressHandler completion:completion];
    });
}

//- (void)createAllOrAddNewTableWithModelClasses:(NSArray <Class>*)modelClasses {
//    [self createAllOrAddNewTableWithModelClasses:modelClasses database:@"Appscomm.sqlite" dbPath:nil];
//}
//
//- (void)createAllOrAddNewTableWithModelClasses:(NSArray <Class>*)modelClasses database:(NSString *)database dbPath:(NSString * _Nullable )dbPath {
//    
//    [LYDatabase database:database dbPath:dbPath];
//    [LYDatabase database].logOn = NO;
//    
//    __block NSInteger oldVersion = [self DBVersionWithDatabase:database andPath:dbPath];
//    
//    if([[LYDatabase database] needUpdateTableArray:modelClasses]) {//需要创建新表->增加新表时候调用
//        //需要更新的表的名字
//        NSArray <Class>*clsNameArr = [[LYDatabase database] needUpdateTable:modelClasses];
//        //新建数据表
//        for (Class class in clsNameArr) {
//            
//            [class createTable];
//        }
//    }
//    
//    [self.stepsArr enumerateObjectsUsingBlock:^(id<LYDBMigrateStepProtocol>  _Nonnull step, NSUInteger index, BOOL * _Nonnull stop) {
//        
//        //当前版本号大于旧的版本号时更新
//        if (step.completeVersion > oldVersion) {
//            NSError *err = nil;
//            [step goUpActionWithCurrentDBVersion:oldVersion Error:&err];
//            if (err) {
//                [step goDownActionWithError:&err];
//                return;
//            }
//            
//            [self setDBVersion:step.completeVersion database:database andPath:dbPath];
//            oldVersion = [self DBVersionWithDatabase:database andPath:dbPath];
//            
//        }
//    }];
//}

#pragma mark --设置数据库版本号--
- (void)setDBVersion:(NSInteger)dbVersion {
    //如果没有迁移表则创建
    [self.database createIfNotExistTable:versionTableName version:dbVersion column:cloumn_Version];
    [self.database updateVersion:dbVersion withTableName:versionTableName column:cloumn_Version];
    
}

- (NSInteger)DBVersion {
    NSInteger dbVersion = [self.database selectWithTableName:versionTableName column:cloumn_Version];
    return dbVersion;
}

@end
